const express = require("express");
const router = express.Router();
const models = require("../models");
const Op = models.Sequelize.Op; // 模糊查询的时候需要用到

// 查询留言列表
router.get("/list", async function (req, res, next) {
  const where = {};
  const currentPage = parseInt(req.query.currentPage) || 1; // 分页参数
  const pageSize = parseInt(req.query.pageSize) || 10; // 分页参数
  const title = req.query.title;
  const type = req.query.type;
  if (title) {
    where.title = {
      [Op.like]: "%" + title + "%",
    };
  }
  if (type) {
    where.type = {
      [Op.like]: type,
    };
  }
  const result = await models.Suggestion.findAndCountAll({
    order: [["id", "desc"]], // 根据某个字段进行排序， desc-降序 asc-升序
    where: where,
    offset: (currentPage - 1) * pageSize,
    limit: pageSize,
  });
  res.json({
    code: 200,
    msg: "操作成功",
    data: {
      total: result.count,
      currentPage: currentPage,
      pageSize: pageSize,
      data: result.rows,
    },
  });
});

// 新增留言
router.post("/", async function (req, res, next) {
  await models.Suggestion.create({
    type: req.body.type,
    title: req.body.title,
    content: req.body.content,
    stuCode: req.body.stuCode,
    name: req.body.name,
    anonymous: req.body.anonymous,
  });
  res.json({
    code: 200,
    msg: "操作成功",
  });
});

// 批量删除留言
router.delete("/", async function (req, res, next) {
  const suggestionList = req.body.suggestionList;
  if (suggestionList) {
    for (const element of suggestionList) {
      const result = await models.Suggestion.findByPk(element);
      if (result) {
        result.destroy(req.body);
      } else {
        res.json({
          code: 400,
          msg: "当前数据不存在",
        });
      }
    }
    res.json({
      code: 200,
      msg: "操作成功",
    });
  }
});
module.exports = router;
